package test4;

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.*;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.ClassUtils;

import java.util.Arrays;

/**
 * @author: mornd
 * @dateTime: 2023/5/11 - 19:05
 * condition 条件装配原理
 */
public class ConditionTest {

    public static void main(String[] args) {
        GenericApplicationContext context = new GenericApplicationContext();
        AnnotationConfigUtils.registerAnnotationConfigProcessors(context.getDefaultListableBeanFactory());
        context.registerBean(Config.class);

        context.refresh();
        Arrays.stream(context.getBeanDefinitionNames()).forEach(System.out::println);
        context.close();
    }


    static class Config {
        @Bean
        @ConditionalOnBean
        public Bean1 bean1() {
            return new Bean1();
        }

        @Bean
        @Conditional(MyCondition.class)
        public Bean1 bean2() {
            return new Bean1();
        }
    }

    static class MyCondition implements Condition {

        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            // 判断当前类路径下是否存在该类
            boolean present = ClassUtils.isPresent("test4.App.ConditionClazz", null);
            return present;
        }
    }
    static class Bean1 { }
    static class ConditionClazz { }
}
